package suites.integration {
	import org.flexunit.asserts.assertTrue;
	import org.flexunit.asserts.fail;
	import org.flexunit.async.Async;
	import org.splink.library.queue.QEvent;
	import org.splink.resource.IResourceProcessor;
	import org.splink.resource.ResourceProcessorEvent;
	import org.splink.resource.ResourceProgress;
	import org.splink.resource.XMLResourceProcessor;

	import flash.events.Event;

	/**
	 * @author Max Kugland
	 */
	public class AbstractIntegrationTest {
		private var _processor : IResourceProcessor;
		private var _handleEventFnc : Function;

		final protected function createProcessor(xml : XML, completeFnc : Function, locale : String = "defaultLocale") : IResourceProcessor {
			_processor = new XMLResourceProcessor(xml, locale);
			_processor.register(QEvent.COMPLETE, completeFnc);			_processor.register(QEvent.COMPLETE, function(e : QEvent) : void {
				_handleEventFnc(new Event(Event.COMPLETE));
			});			_processor.register(QEvent.ERROR, onError);			_processor.register(ResourceProcessorEvent.PROGRESS, onProgress);
			return _processor;
		}

		private function onProgress(e : ResourceProcessorEvent) : void {
			var rp : ResourceProgress = e.resourceProgress;
			assertTrue(rp.current <= rp.total);			assertTrue(rp.currentPercent <= 100);			assertTrue(rp.totalPercent <= 100);
			// as the regeneration of the sample fonts and assets always yields different filesize values the following assertions aren't safe //			assertTrue(rp.totalLoadedBytes <= rp.totalBytes);//			assertTrue(rp.currentLoadedBytes <= rp.currentTotalBytes);
		}

		private function onError(e : QEvent) : void {
			fail(e.errorMessage);
		}

		[After]
		final public function after() : void {
			_processor.finalize();
		}

		final protected function handleAsync(timeout : int) : Function {
			return _handleEventFnc = Async.asyncHandler(this, function():void {
			}, timeout, null, handleTimeout);
		}

		private function handleTimeout( passThroughData : Object ) : void {
			fail("Timeout reached before event");			
		}
	}
}
